package com.elminster.common.db.analyze;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import com.elminster.common.db.annotation.Column;
import com.elminster.common.db.annotation.Entry;
import com.elminster.common.db.annotation.Key;
import com.elminster.common.db.annotation.KeyPolicy;
import com.elminster.common.db.exception.SqlAnalyzeException;

abstract public class ORMSqlAnalyzer extends BaseSqlAnalyzer implements ISqlAnalyzer {
	
	protected List<String> keys = new ArrayList<String>();

	@Override
	public void parser(Method invokedMethod, Object... methodArguments) {
		boolean hasEntry = false;
		for (Object obj : methodArguments) {
			if (null == obj.getClass().getAnnotation(Entry.class)) {
				continue;
			}
			hasEntry = true;
			mapping(obj);
			break;
		}
		if (!hasEntry) {
			// TODO Error
			throw new SqlAnalyzeException("");
		}
	}

	abstract protected void mapping(Object obj);
	
	protected String getTableName(Object obj) {
		Entry entry = obj.getClass().getAnnotation(Entry.class);
		if (null == entry) {
			throw new SqlAnalyzeException("");
		}
		return entry.tableName();
	}
	
	protected boolean isKey(Field field) {
		Key key = field.getAnnotation(Key.class);
		return null != key;
	}
	
	protected KeyPolicy getKeyPolicy(Field field) {
		Key key = field.getAnnotation(Key.class);
		return key.policy();
	}
	
	protected boolean isColumn(Field field) {
		Column column = field.getAnnotation(Column.class);
		return null != column;
	}
	
	protected String getColumnName(Field field) {
		String columnName = null;
		Column column = field.getAnnotation(Column.class);
		if (null != column) {
			columnName = column.name();
		}
		return columnName;
	}
}
